package kitwee.com.kanpad.orderDetail;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.BaseFragment;
import kitwee.com.kanpad.BuildConfig;
import kitwee.com.kanpad.R;
import kitwee.com.kanpad.bean.BomvoListAdapter;
import kitwee.com.kanpad.bean.ListDetailBean;
import kitwee.com.kanpad.bean.LoginBean;
import kitwee.com.kanpad.bean.MyStopAdapter;
import kitwee.com.kanpad.bean.ReasonAdapter;
import kitwee.com.kanpad.bean.TaskListBean;
import okhttp3.Call;
import utils.FlavorHelper;
import utils.SPUtils;

/**
 * @author GanQuan
 * @date 2018/1/22
 */

public class OrderDetailFragment extends BaseFragment implements View.OnClickListener {


    @BindView(R.id.task_name)
    TextView taskName;
    @BindView(R.id.task_no)
    TextView taskNo;
    @BindView(R.id.task_order)
    TextView taskOrder;
    @BindView(R.id.production_name)
    TextView productionName;
    @BindView(R.id.production_no)
    TextView productionNo;
    @BindView(R.id.equipment_name)
    TextView equipmentName;
    @BindView(R.id.plan_start)
    TextView planStart;
    @BindView(R.id.plan_end)
    TextView planEnd;
    @BindView(R.id.plan_time)
    TextView planTime;
    @BindView(R.id.plan_no)
    TextView planNo;
    @BindView(R.id.actual_start)
    TextView actualStart;
    @BindView(R.id.actual_end)
    TextView actualEnd;
    @BindView(R.id.actual_time)
    TextView actualTime;
    @BindView(R.id.actual_no)
    TextView actualNo;
    @BindView(R.id.task_startus)
    TextView taskStatus;
    @BindView(R.id.good_pro)
    TextView goodPro;
    @BindView(R.id.bad_pro)
    TextView badPro;
    @BindView(R.id.actual_pro)
    TextView actualPro;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.pause_title)
    TextView pauseTitle;
    @BindView(R.id.recycleview_reason)
    RecyclerView recycleviewReason;
    @BindView(R.id.cancel)
    TextView btNotSure;
    @BindView(R.id.tv_sure)
    TextView btSure;
    @BindView(R.id.rl_reason)
    RelativeLayout rlReason;
    @BindView(R.id.stop_recycleview_reason)
    RecyclerView stopRecycleviewReason;

    @BindView(R.id.sub_number)
    EditText subNumber;
    @BindView(R.id.sub_good_number)
    EditText subGoodNumber;
    @BindView(R.id.sub_bad_number)
    EditText subBadNumber;
    @BindView(R.id.sub_time)
    EditText subTime;

    @BindView(R.id.sub_sure)
    TextView subSure;
    @BindView(R.id.sub_cancel)
    TextView subCancel;


    @BindView(R.id.rl_work)
    RelativeLayout rlWork;


    private View layout;
    private Context context;
    private ReasonAdapter adapter;
    private MyStopAdapter adapters;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.fragment_order_detail_layout, container, false);
        ButterKnife.bind(this, layout);
        return layout;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        if (layout != null && rowsBean != null) {
//            //报工实际产量
//            if(FlavorHelper.isGoertek()){
//                subNumber.setText(""+rowsBean.getActual_production());
//            }
//
//            taskName.setText(context.getString(R.string.task_name) + rowsBean.getTask_name());
//            taskOrder.setText(context.getString(R.string.task_order) + rowsBean.getOrder_number());
//
//            productionNo.setText(context.getString(R.string.pro_no) + rowsBean.getProduct_number());
//            equipmentName.setText(getString(R.string.equipment_name) + rowsBean.getDevice_name());
//
//            taskStatus.setText(getString(R.string.task_status) + rowsBean.getTask_status_value());
//            planStart.setText(context.getString(R.string.plan_start) + rowsBean.getScheduled_start_time_text());
//            planEnd.setText(context.getString(R.string.plan_end) + rowsBean.getScheduled_end_time_text());
//
//            planNo.setText(context.getString(R.string.plan_number) + (int) Math.round(rowsBean.getScheduled_production()));
//            planTime.setText(context.getString(R.string.plan_time) + rowsBean.getPlan_time());
//
//            if (rowsBean.getActual_start_time_text() != null) {
//                actualStart.setText(context.getString(R.string.actual_start) + rowsBean.getActual_start_time_text());
//            } else {
//                actualStart.setText(context.getString(R.string.actual_start) + " 暂无");
//            }
//            if (rowsBean.getActual_end_time_text() != null) {
//                actualEnd.setText(context.getString(R.string.actual_end) + rowsBean.getActual_end_time_text());
//            } else {
//                actualEnd.setText(context.getString(R.string.actual_end) + " 暂无");
//            }
//
//            actualNo.setText(context.getString(R.string.actual_number) + rowsBean.getActual_production());
//
//        }
        EventBus.getDefault().postSticky(new OrderRequest("request"));
        initRecycleView();
    }


    private void setSerialPortPaused(String statusKey) {
        // 设备自动暂停，需补写暂停原因
        if ("pause_device_auto".equals(statusKey)) {
            rlReason.setVisibility(View.VISIBLE);
            SerialPortHelper.getInstance(getContext()).setPaused(true);
        }
//        else if ("in_process".equals(statusKey)) {
//            SerialPortHelper.getInstance(getContext()).setPaused(false);
//        }
    }

    public static TaskListBean.RowsBean rowsBean;

    public static OrderDetailFragment newInstance(TaskListBean.RowsBean beans) {
        rowsBean = beans;
        return new OrderDetailFragment();
    }


    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


    private ListDetailBean listDetailBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowMessageEvent(OrderDetailEvent orderDetailEvent) {
        ListDetailBean listDetailBean = orderDetailEvent.getListDetailBean();
        LogUtils.e("任务详情页 : " + orderDetailEvent.getListDetailBean().getTaskDetailChangeStatusBtnList());
        this.listDetailBean = listDetailBean;
        if (listDetailBean != null && layout != null) {

            // 切换了任务状态,更新之
            taskStatus.setText(getString(R.string.task_status) + listDetailBean.getTask_status_value());

            setChangButton(listDetailBean);
            if (listDetailBean.getActual_production_person() != null) {
                actualPro.setText(context.getString(R.string.actual_number_person) + listDetailBean.getActual_production_person());
            } else {
                actualPro.setText(context.getString(R.string.actual_number_person) + " 暂无");
            }

            if (listDetailBean.getGoodProductAmount() != null) {
                goodPro.setText(context.getString(R.string.good_pro) + listDetailBean.getGoodProductAmount());
            } else {
                goodPro.setText(context.getString(R.string.good_pro) + "暂无");
            }

            if (listDetailBean.getBadProductAmount() != null) {
                badPro.setText(context.getString(R.string.bad_pro) + listDetailBean.getBadProductAmount());
            } else {
                badPro.setText(context.getString(R.string.bad_pro) + "暂无");
            }

            if (listDetailBean.getRun_time() != null) {
                actualTime.setText(getString(R.string.actual_time) + listDetailBean.getRun_time() + "/分钟");
            } else {
                actualTime.setText(getString(R.string.run_time) + "暂无");
            }
            actualNo.setText(context.getString(R.string.actual_number) + listDetailBean.getActual_production());

            if (listDetailBean.getActual_start_time_text() != null) {
                actualStart.setText(context.getString(R.string.actual_start) + listDetailBean.getActual_start_time_text());
            } else {
                actualStart.setText(context.getString(R.string.actual_start) + " 暂无");
            }
            if (listDetailBean.getActual_end_time_text() != null) {
                actualEnd.setText(context.getString(R.string.actual_end) + listDetailBean.getActual_end_time_text());
            } else {
                actualEnd.setText(context.getString(R.string.actual_end) + " 暂无");
            }

            if (listDetailBean.getPlan_time() != null) {
                planTime.setText(context.getString(R.string.plan_time) + rowsBean.getPlan_time());
            }

            setSerialPortPaused(listDetailBean.getTask_status_key());
        }
    }

    private void setChangButton(ListDetailBean listDetailBean) {
        List<ListDetailBean.TaskDetailChangeStatusBtnListBean> taskDetailChangeStatusBtnList = listDetailBean.getTaskDetailChangeStatusBtnList();
        if (taskDetailChangeStatusBtnList != null) {
            llContent.removeAllViews();
            addButtonView(taskDetailChangeStatusBtnList);
        }

        List<ListDetailBean.PauseStatusRemarksBean> pauseStatusRemarks = listDetailBean.getPauseStatusRemarks();
        if (pauseStatusRemarks != null) {
            pauserowsBeenTrue.clear();
            pauserowsBeenTrue.addAll(pauseStatusRemarks);
            adapter.notifyDataSetChanged();
        }
        if (listDetailBean.getTask_status_key().startsWith("pause") && !TextUtils.equals("pause_device_auto", listDetailBean.getTask_status_key())) {
            rlReason.setVisibility(View.GONE);
        }
    }

    private void addButtonView(List<ListDetailBean.TaskDetailChangeStatusBtnListBean> rowsBeen) {
        if (rowsBeen.size() > 0) {
            // TODO 动态添加布局(java方式)
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            LinearLayout view = new LinearLayout(context);
            view.setLayoutParams(lp);//设置布局参数
            view.setOrientation(LinearLayout.HORIZONTAL);// 设置子View的Linearlayout// 为垂直方向布局
            LinearLayout.LayoutParams vlp = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            vlp.setMargins(15, 15, 15, 0);

            for (int i = 0; i < rowsBeen.size(); i++) {
                addTestView(rowsBeen.get(i).getStatus_key(), rowsBeen.get(i).getStatus_value(), vlp);
            }
        }
    }

    private int calculateDpToPx(int padding_in_dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (padding_in_dp * scale + 0.5f);
    }

    private void addTestView(String key, String value, LinearLayout.LayoutParams vlp) {
        TextView textWhat = new TextView(context);
        textWhat.setLayoutParams(vlp);
        textWhat.setTextSize(13);
        textWhat.setPadding(calculateDpToPx(5), calculateDpToPx(10), calculateDpToPx(5), calculateDpToPx(10));

        setTextId(textWhat, key, value);
        textWhat.setTextColor(getResources().getColor(R.color.white));
        textWhat.setBackgroundColor(getResources().getColor(R.color.item_back));
        textWhat.setGravity(Gravity.CENTER_HORIZONTAL);

        textWhat.setOnClickListener(this);
        llContent.addView(textWhat);

    }

    private void setTextId(TextView textWhat, String key, String value) {
        if (key != null) {
            if (TextUtils.equals("pause", key)) {//暂停
                textWhat.setId(R.id.status_pause);
                textWhat.setText(value);
            } else if (TextUtils.equals("not_started", key)) {  //未开始
                textWhat.setId(R.id.status_start_not_start);
                textWhat.setText(value);
            } else if (TextUtils.equals("started", key)) {  //开始
                textWhat.setId(R.id.status_prepare);
                textWhat.setText(value);
            } else if (TextUtils.equals("debug_machine", key)) {  //调机
                textWhat.setId(R.id.status_fix);
                textWhat.setText(value);
            } else if (TextUtils.equals("in_process", key)) {  //生产
                textWhat.setId(R.id.status_product_start);
                textWhat.setText(value);
            } else if (TextUtils.equals("complete", key)) {  //完成
                textWhat.setId(R.id.status_finsh);
                textWhat.setText(value);
            } else if (TextUtils.equals("stop", key)) {  //中止
                textWhat.setId(R.id.status_stop);
                textWhat.setText(value);
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.status_start_not_start:
                LogUtils.e("not_started");
//                setTaskStatus("not_started");
                break;
            case R.id.status_prepare:
                LogUtils.e("started");
//                setTaskStatus("started");
                break;
            case R.id.status_fix:
                LogUtils.e("debug_machine");
//                setTaskStatus("debug_machine");
                break;
            case R.id.status_product_start:
                LogUtils.e("in_process");
//                setTaskStatus("in_process");
                break;
            case R.id.status_finsh:
                rlReason.setVisibility(View.GONE);

                rlWork.setVisibility(View.VISIBLE);
                LogUtils.e("complete");
//                setTaskStatus("complete"); // 应该是先"报工"再"完成"
                break;
            case R.id.status_stop:
                LogUtils.e("stop");
                rlReason.setVisibility(View.VISIBLE);

                break;
            case R.id.status_pause:
                rlReason.setVisibility(View.VISIBLE);

                break;


        }
    }

    /**
     * 报工
     */

    private void submitProduction() {

        if (subNumber.getText().toString() != null) {
            String number = subNumber.getText().toString();
            String goodNumber = subGoodNumber.getText().toString();
            String badNumber = subBadNumber.getText().toString();
            String continuedTime = subTime.getText().toString();

            String user = SPUtils.getString(getActivity(), "user");
            String key = SPUtils.getString(getActivity(), "key");
            final long time = System.currentTimeMillis();
            final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
            String timer = String.valueOf(time);
            OkHttpUtils.get()
                    .tag(this)
//                    .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/addproduction")
                    .url(getAPiEndpoint() + "/deviceStatusRecords/addproduction")
                    .addParams("pun", user)
                    .addParams("pd", digest)
                    .addParams("t", timer)
                    .addParams("confirmed_production", number)
                    .addParams("badProductAmount", badNumber)
                    .addParams("goodProductAmount", goodNumber)
                    .addParams("run_time", continuedTime)
                    .addParams("taskId", rowsBean.getId())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            LogUtils.e("报工失败 ; " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {

                            JSONObject jsonObj = JSON.parseObject(response);
                            String data = jsonObj.getString("statusCode");
                            if (TextUtils.equals("200", data)) {
                                LogUtils.e("报工成功 ; " + response);
                                setTaskStatus("complete");
                                resetSubText();

                                rlWork.setVisibility(View.GONE);

                            } else {
                                rlWork.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }


    private String getAPiEndpoint() {
        return BuildConfig.API_ENDPOINT;
    }

    private void resetSubText() {
        subNumber.setText("");
        subBadNumber.setText("");
        subGoodNumber.setText("");
        subTime.setText("");
    }


    @OnClick({R.id.cancel, R.id.tv_sure, R.id.sub_sure, R.id.sub_cancel})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                rlReason.setVisibility(View.GONE);
                break;
            case R.id.tv_sure:
                if (dick_value != null && dick_value != null) {
//                    setTaskStatusStopAndPause(dict_key, dick_value);
                    rlReason.setVisibility(View.GONE);
                } else {
                    ToastUtils.showShort("请先选择暂停原因");
                }

                break;

            case R.id.sub_sure:

                String s = subNumber.getText().toString();
                String s1 = subBadNumber.getText().toString();
                String s2 = subGoodNumber.getText().toString();
                String s3 = subTime.getText().toString();
                if (TextUtils.equals("", s) && TextUtils.equals("", s1) && TextUtils.equals("", s2) && TextUtils.equals("", s3)) {
                    ToastUtils.showShort("报工参数不能为空");
                } else {
//                    submitProduction();
                }
                break;
            case R.id.sub_cancel:

                rlWork.setVisibility(View.GONE);
                break;
        }
    }

    private void setTaskStatus(final String status_key) {
        String task_id = rowsBean.getId();
        String user = SPUtils.getString(context, "user");
        String key = SPUtils.getString(context, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/productionTask/changeTaskStatus")
                .url(getAPiEndpoint() + "/productionTask/changeTaskStatus")
                .addParams("EQ_task_id", task_id)
                .addParams("EQ_task_status_key", status_key)
                .addParams("pd", digest)
                .addParams("pun", user)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        LogUtils.e("切换状态失败 : " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                        if (TextUtils.equals("200", loginBean.getStatusCode())) {
                            ToastUtils.showShort(loginBean.getMessage() + "");
                            EventBus.getDefault().postSticky(new OrderRequest("request"));
//                            initNetData();
                            if ("complete".equals(status_key)) {
                                getActivity().finish();
                            }

                        } else if (TextUtils.equals("300", loginBean.getStatusCode())) {
                            ToastUtils.showShort(loginBean.getMessage() + "");
                            LogUtils.e("操作失败 : " + loginBean.getMessage());
                        }
                    }
                });
    }

    private List<ListDetailBean.PauseStatusRemarksBean> pauserowsBeenTrue;


    private String dick_value;
    private String dict_key;

    private void initRecycleView() {
        pauserowsBeenTrue = new ArrayList<>();
        GridLayoutManager gridLayoutManagers = new GridLayoutManager(context, 3);
        recycleviewReason.setLayoutManager(gridLayoutManagers);
        adapter = new ReasonAdapter(getActivity(), pauserowsBeenTrue);
        recycleviewReason.setAdapter(adapter);

        adapter.setOnItemClickLitener(new BomvoListAdapter.OnItemClickLitener() {


            @Override
            public void onItemClick(View view, int position) {

                dict_key = pauserowsBeenTrue.get(position).getDict_key();
                dick_value = pauserowsBeenTrue.get(position).getDict_value();

            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }


    private void setTaskStatusStopAndPause(String status_key, String value) {
        String task_id = rowsBean.getId();
        String user = SPUtils.getString(context, "user");
        String key = SPUtils.getString(context, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/productionTask/changeTaskStatus")
                .url(getAPiEndpoint() + "/productionTask/changeTaskStatus")
                .addParams("EQ_task_id", task_id)
                .addParams("EQ_task_status_key", status_key)
                .addParams("EQ_task_status_remarks", value)
                .addParams("pd", digest)
                .addParams("pun", user)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                        if (TextUtils.equals("200", loginBean.getStatusCode())) {


                            ToastUtils.showShort("" + loginBean.getMessage());
                            rlReason.setVisibility(View.GONE);
                            EventBus.getDefault().postSticky(new OrderRequest("request"));
                            SerialPortHelper.getInstance(getContext()).setPaused(false);
//                            getActivity().finish();
                        } else if (TextUtils.equals("300", loginBean.getStatusCode())) {
                            ToastUtils.showShort("" + loginBean.getMessage());
                            rlReason.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

}
